package com.me.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.me.bbs.anno.RequireLogin;
import com.me.bbs.common.Resp;
import com.me.bbs.entity.User;
import com.me.bbs.exceptions.FileUploadException;
import com.me.bbs.service.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Liming Wang
 * @Description
 * @Create 2023/1/10 17:24
 */
@RestController

public class FileController {
    @Value("${static_path}")
    private String path;
    @Resource
    private IUserService userService;

    @PostMapping("/upload/{folder}")
    @RequireLogin
    public Resp<?> uploadAvatar(
            @PathVariable("folder") String folder,
            @RequestParam("file") MultipartFile file) throws IOException {
        File f = new File(path + File.separatorChar + folder);

        if (!f.exists()) {
            if (!f.mkdir())
                throw new IOException();
        }
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fileName = UUID.randomUUID()
                .toString()
                .replaceAll("-", "")
                + originalFilename
                .substring(originalFilename.lastIndexOf("."));
        String target = path + File.separatorChar + folder + File.separatorChar + fileName;
        try {
            file.transferTo(new File(target));
        } catch (IOException e) {
            throw new FileUploadException("文件上传错误");
        }
        String srcPath =  "/image/" + folder + "/" + fileName;
        return Resp.success(srcPath, "成功");

    }

    @GetMapping("/image/{folder}/{file}")
    public void getAvatar(@PathVariable("file") String file,
                          @PathVariable("folder") String folder,
                          HttpServletResponse response) throws IOException {
        String fullPath = path + File.separatorChar +
                folder +
                File.separatorChar +
                file;
        ServletOutputStream os = response.getOutputStream();
        try (InputStream is = Files.newInputStream(Paths.get(fullPath));) {
            byte[] bytes = new byte[256];
            while ((is.read(bytes)) != -1) {
                os.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
